﻿using ExtensionTools;
using Microsoft.EntityFrameworkCore;
using NewsEntity.Models;
using NewsSevicer.Interface;
using NewsSevicer.ResultClass;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace NewsSevicer
{
  

    public class OnlineUserService : IOnlineUserService
    {
        private readonly NewsContext _context;

       private SignSendJWTToken _signSendJWTToken;
        public OnlineUserService(SignSendJWTToken signSendJWTToken)
        {
            _context = new NewsContext();
            _signSendJWTToken = signSendJWTToken;
        }

        public OnlineUsers CreateUser(OnlineUsers user)
        {
       
            try
            {
                user.UserID = Guid.NewGuid().ToString();
                user.CreatedAt = DateTime.UtcNow;
                user.UpdatedAt = DateTime.UtcNow;
                    _context.OnlineUsers.Add(user);
                    _context.SaveChanges();
            }
            catch (Exception e)
            {

                throw new Exception($"出现错误{e}");
            }
            return user;
        }

        public  OnlineUsers GetUserById(string userId)
        {
            var user =  _context.OnlineUsers.Single(x => x.UserID == userId);
            return user;
        }

        public async Task<IEnumerable<OnlineUsers>> GetAllUsersAsync()
        {
            return await _context.OnlineUsers.ToListAsync();
        }

        public async Task<OnlineUsers> UpdateUserAsync(OnlineUsers user)
        {
            var existingUser = await _context.OnlineUsers.FirstOrDefaultAsync(u => u.UserID == user.UserID);

            if (existingUser == null)
            {
                throw new Exception("User not found");
            }

            existingUser.Username = user.Username;
            existingUser.Password = user.Password;
            existingUser.Email = user.Email;
            existingUser.LoginTime = user.LoginTime;
            existingUser.LogoutTime = user.LogoutTime;
            existingUser.Status = user.Status;
            existingUser.IPAddress = user.IPAddress;
            existingUser.DeviceType = user.DeviceType;
            existingUser.BrowserInfo = user.BrowserInfo;
            existingUser.SessionID = user.SessionID;
            existingUser.Location = user.Location;
            existingUser.LastActiveTime = user.LastActiveTime;
            existingUser.Role = user.Role;
            existingUser.UpdatedAt = DateTime.UtcNow;

            _context.OnlineUsers.Update(existingUser);
            await _context.SaveChangesAsync();

            return existingUser;
        }




        public async Task<bool> DeleteUserAsync(string userId)
        {
            var user = await _context.OnlineUsers.FirstOrDefaultAsync(u => u.UserID == userId);

            if (user == null)
            {
                return false;
            }

            _context.OnlineUsers.Remove(user);
            await _context.SaveChangesAsync();

            return true;
        }

        public RequestResult<loginInfoDto> Login(OnlineUsers user)
        {
     
            if (user.Username!=string.Empty&&user.Password!=string.Empty) {
           var res =   _context.OnlineUsers.FirstOrDefault(x => x.Username == user.Username && x.Password == user.Password);

                if (res != null)
                {
                  var  token = _signSendJWTToken.GenerateJwtToken(res.Username);
                   DateTime dateTime= DateTime.Now;
                    var info = DtoExtensions.ToDto(res);
                    loginInfoDto InfoDto = new loginInfoDto {  Info= info, Token=token, TokenExpirationTime= dateTime.AddDays(1)};
                    LogHelper.Info($"{info.UserName}登录成功");
                    return new RequestResult<loginInfoDto>().success<loginInfoDto>(InfoDto);
                }
            }

            if (user.Email != string.Empty && user.Password != string.Empty)
            {
                var res = _context.OnlineUsers.FirstOrDefault(x => x.Email == user.Email && x.Password == user.Password);
                if (res != null) {
                    var token = _signSendJWTToken.GenerateJwtToken(res.Username);
                    DateTime dateTime = new DateTime();
                    var info = DtoExtensions.ToDto(res);
                    loginInfoDto InfoDto = new loginInfoDto { Info = info, Token = token, TokenExpirationTime = dateTime.AddDays(1) };
                    LogHelper.Info($"{info.Email}登录成功");
                    return new RequestResult<loginInfoDto>().success<loginInfoDto>(InfoDto);
                }
            }
            LogHelper.Info($"{user.Username}{user.Email}登录失败账号或者密码错误");
            return new RequestResult<loginInfoDto>().fail<loginInfoDto>();
        }
    }
}
